package com.nf.mvc.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

import static java.util.Objects.requireNonNull;

public abstract class FileUtils {
    public static void copy(InputStream input, OutputStream output) throws IOException {
        requireNonNull(input, "输入流不能是null的");
        requireNonNull(output, "输出流不能是null的");

        try (InputStream in = input; OutputStream out = output) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
        }
    }

    public static String getMediaType(String filename) {
        // guessContentTypeFromName是从文件名猜测其内容类型，如果为null就猜测失败
        String mediaType = URLConnection.guessContentTypeFromName(filename);
        if (mediaType == null) {
            mediaType = "application/octet-stream";
        }
        return mediaType;
    }

    public static String getFilename(String path) {
        if (path == null || path.isEmpty()) {
            throw new IllegalArgumentException("空的文件路径是没办法取得其文件名的");
        }

        int separatorIndex = path.lastIndexOf("/");
        return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path);
    }

    public static InputStream getInputStreamFromRealPath(String realPath) {
        InputStream inputStream;
        try {
            // 要用Path（java.nio),不能用File[new File(realPath)]，因为jetty下会报文件找不到的异常
            Path path = Paths.get(realPath);
            inputStream = Files.newInputStream(path);
        } catch (IOException e) {
            throw new IllegalArgumentException("路径可能不对:" + realPath + " 无法生成输入流", e);
        }
        return inputStream;
    }
}
